#!/bin/sh

uci_op="$1" #set get show delete revert getkey

uci_command="$2"
DB_PATH="/tmp/myuci.db"

db_sqlite3()
{
	sqlite3 "$1" "$2"
	while [ $? -ne 0 ];
	do
		logger "sqlite3 $* failed, retry"
		sqlite3 "$1" "$2"
	done
}

if [ "${uci_op}" == "show" ];then
	if [ "${uci_command}" == "" ]; then
		db_sqlite3 ${DB_PATH} "SELECT * FROM uci"
	else
		db_sqlite3 ${DB_PATH} "SELECT * FROM uci WHERE uci_key LIKE '${uci_command}.%'"
	fi
	exit
fi


if [ "${uci_op}" == "set" ];then
	uci_key="$(echo "$uci_command" | awk -F= '{print $1}')"
	uci_value="$(echo "$uci_command" | awk -F= '{print $2}' | tr -d '"' | tr -d "'")"
	db_sqlite3 ${DB_PATH} "REPLACE INTO uci (uci_key, uci_value) values ('${uci_key}', '${uci_value}')"
	exit
fi

if [ "${uci_op}" == "get" ];then
	db_sqlite3 ${DB_PATH} "SELECT uci_value FROM uci WHERE uci_key='${uci_command}'"
	exit
fi

if [ "${uci_op}" == "delete" ];then
	db_sqlite3 ${DB_PATH} "DELETE FROM uci WHERE uci_key='${uci_command}'"
	db_sqlite3 ${DB_PATH} "DELETE FROM uci WHERE uci_key LIKE '${uci_command}.%'"
	exit
fi

if [ "${uci_op}" == "revert" ];then
	db_sqlite3 ${DB_PATH} "DELETE FROM uci WHERE uci_key LIKE '${uci_command}.%'"
	exit
fi

if [ "${uci_op}" == "getkey" ];then
	uci_key="$(echo "$uci_command" | awk -F= '{print $1}')"
	uci_value="$(echo "$uci_command" | awk -F= '{print $2}' | tr -d '"' | tr -d "'")"
	db_sqlite3 ${DB_PATH} "SELECT uci_key FROM uci WHERE uci_key LIKE '${uci_key}.%' and uci_value='${uci_value}'"
	exit
fi
